package gen

import (
	"errors"
	"fmt"
	"gitee.com/pkg/utils/flag"
	"gitee.com/runx/dm/pkg/entry"
	"gitee.com/runx/dm/pkg/visitor"
	"github.com/spf13/cobra"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var (
	xDir     string
	xFile    string
	xPkgName string
	xRef     bool
	dmCmd    = &cobra.Command{
		Use:   "gen",
		Short: "gen go types from cue define",
		RunE: func(c *cobra.Command, args []string) error {
			flag.PrintFlags(c.Flags())

			if _, err := os.Stat(xFile); err != nil {
				panic(errors.New(fmt.Sprintf("file:%s not found", xFile)))
			}
			fileAbsPath, err := filepath.Abs(xFile)

			if err != nil {
				panic(err)
			}

			if xPkgName == "" {
				dirPath, _ := filepath.Split(fileAbsPath)
				_, xPkgName = filepath.Split(strings.TrimSuffix(dirPath, "/"))
			}

			w := visitor.NewWriter(xPkgName, xRef)

			visitor.From(xFile).Accept(w)

			err = ioutil.WriteFile(fmt.Sprintf("%s.go", strings.TrimSuffix(fileAbsPath, ".cue")), []byte(w.Gen().String()), 0755)
			if err != nil {
				panic(err)
			}
			return nil
		},
	}
)

func init() {
	dmCmd.PersistentFlags().StringVarP(&xDir, "dir", "d", "", "cue file dir path")
	dmCmd.PersistentFlags().StringVarP(&xFile, "file", "f", "", "cue file path")
	dmCmd.PersistentFlags().StringVarP(&xPkgName, "package", "p", "", "gen go file's package")
	dmCmd.PersistentFlags().BoolVarP(&xRef, "ref", "r", false, "slice map point flag")
	entry.AddCmd(dmCmd)
}
